<template>
  <canvas :id="'container'+index"/>
</template>

<script>
  import F2 from '@antv/f2/lib/index-all';

  export default {
    name: 'index',
    mounted() {
      this.$nextTick(() => {
        this.init();
      });
    },
    props: {
      index: {
        type: Number,
        default: 0
      },
      data: {
        type: Object,
        default: () => ({})
      }
    },
    methods: {
      init() {
        const chart = new F2.Chart({
          id: 'container' + this.index,
          pixelRatio: window.devicePixelRatio
        });

        const { data, fields } = this.data;
        chart.source(data, {
          [fields[1]]: {
            tickCount: 5
          }
        });
        chart.tooltip(false);
        chart.interval().position(fields.join('*'));
        chart.render();

        // 绘制柱状图文本
        const offset = -5;
        const canvas = chart.get('canvas');
        const group = canvas.addGroup();
        data.forEach(obj => {
          const point = chart.getPosition(obj);
          group.addShape('text', {
            attrs: {
              x: point.x,
              y: point.y + offset,
              text: obj[fields[1]],
              textAlign: 'center',
              textBaseline: 'bottom',
              fill: '#808080'
            }
          }); // 缓存该 shape, 便于后续查找
        });
      }
    }
  };
</script>

<style scoped lang="less">
  canvas {
    width: 100%;
    background: #fff;
  }
</style>
